package net.bluemind.ysnp;

import java.io.IOException;

import net.bluemind.unixsocket.UnixServerSocket;
import net.bluemind.ysnp.impl.AuthChainBuilder;

import org.eclipse.equinox.app.IApplication;
import org.eclipse.equinox.app.IApplicationContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * "You Shall Not Pass" saslauthd daemon
 * 
 * @author tom
 * 
 */
public class YSNPDaemon implements IApplication {

	private final Logger logger = LoggerFactory.getLogger(getClass());

	private AuthChainBuilder at;

	@Override
	public Object start(IApplicationContext context) throws Exception {
		logger.info("YSNP daemon starting");

		YSNPConfiguration conf = new YSNPConfiguration();
		logger.info("UNIX socket will be created on " + conf.getSocketPath());

		try {
			// let's create the unix socket
			UnixServerSocket socket = new UnixServerSocket(conf.getSocketPath());
			// and handle incoming authenfication requests
			at = new AuthChainBuilder(conf, socket);
			at.start();
			Runtime.getRuntime().addShutdownHook(new Thread() {
				public void run() {
					try {
						at.shutdown();
						logger.info("Shutdown complete.");
					} catch (IOException e) {
						logger.error("Problem shutdown auth director", e);
					}
				}
			});
		} catch (IOException ioe) {
			logger.error("could not start daemon: " + ioe.getMessage());
		}

		return EXIT_OK;
	}

	@Override
	public void stop() {
		logger.info("YSNP daemon shutdown.");
	}

}
